/*
 * Copyright 2010 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.spikegpsongoogleappengine.fb;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.spikegpsongoogleappengine.R;
import com.spikegpsongoogleappengine.fb.SessionEvents.AuthListener;
import com.spikegpsongoogleappengine.fb.SessionEvents.LogoutListener;

/**
 * Usage for changing 
 * mLoginButton.init(this, mFacebook, new String[]{"publish_stream", "read_stream", "offline_access"});
 * @author Sinisa
 *
 */
public class PostToWallButton extends ImageButton {
    
	private static final String TAG = "PostToWallButton";
    private Facebook mFb = new Facebook(FacebookHelper.APP_ID);
    private Handler mHandler = new Handler();
    private SessionListener mSessionListener = new SessionListener();
    private String[] mPermissions = new String[]{"publish_stream", "read_stream", "offline_access"};
    private Activity mActivity;
    
    public PostToWallButton(Context context) {
        super(context);
    }
    
    public PostToWallButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    public PostToWallButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    
    public void init(final Activity activity) {
        mActivity = activity;
        
        setBackgroundColor(Color.TRANSPARENT);
        setAdjustViewBounds(true);
        //In both cases if the user is loged in or not, put the discount icon
        setImageResource(mFb.isSessionValid() ?
                         R.drawable.discount_icon : 
                         R.drawable.discount_icon);
        drawableStateChanged();
        
        SessionEvents.addAuthListener(mSessionListener);
        SessionEvents.addLogoutListener(mSessionListener);
        setOnClickListener(new ButtonOnClickListener());
    }
    
    private final class ButtonOnClickListener implements OnClickListener {
        public void onClick(View arg0) {
            if (!mFb.isSessionValid()) {
            	mFb.authorize(mActivity, mPermissions,
            			new LoginDialogListener());
            } else {
            	postOnWall("Session valid");
            }
        }
    }

    private final class LoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            SessionEvents.onLoginSuccess();
            Log.d(TAG, "Testing status change");
        	postOnWall("Tesssss New");
        	Log.d(TAG, "Testing status change");
        }

        public void onFacebookError(FacebookError error) {
            SessionEvents.onLoginError(error.getMessage());
        }
        
        public void onError(DialogError error) {
            SessionEvents.onLoginError(error.getMessage());
        }

        public void onCancel() {
            SessionEvents.onLoginError("Action Canceled");
        }
    }
    
    private class LogoutRequestListener extends BaseRequestListener {
        public void onComplete(String response, final Object state) {
            // callback should be run in the original thread, 
            // not the background thread
            mHandler.post(new Runnable() {
                public void run() {
                    SessionEvents.onLogoutFinish();
                }
            });
        }
    }
    
    private class SessionListener implements AuthListener, LogoutListener {
        
		public void onAuthSucceed() {
            setImageResource(R.drawable.discount_icon);
            SessionStore.save(mFb, getContext());
        }

        public void onAuthFail(String error) {
        	Log.e(TAG, error);
        }
        
        public void onLogoutBegin() {           
        }
        
        public void onLogoutFinish() {
            SessionStore.clear(getContext());
            setImageResource(R.drawable.discount_icon);
        }
    }
    
    public void postOnWall(String msg) {
		Log.d("Tests", "Testing graph API wall post");
		try {
			String response = mFb.request("me");
			Bundle parameters = new Bundle();
			parameters.putString("message", msg);
			parameters.putString("description", "test test test");
			response = mFb.request("me/feed", parameters, "POST");
			Log.d("Tests", "got response: " + response);
			if (response == null || response.equals("")
					|| response.equals("false")) {
				Log.v("Error", "Blank response");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    
}
